package com.hotel.couponsystem.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.common.status.RedisKey;
import com.common.status.ResultMsg;
import com.common.status.StatusCode;
import com.common.utils.ResultUtils;
import com.common.utils.ResultVo;
import com.hotel.config.websocket.WebSocketProcess;
import com.hotel.couponsystem.pojo.CouponStock;
import com.hotel.couponsystem.service.CouponStockService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * (CouponStock)表控制层
 *
 * @author makejava
 * @since 2022-09-30 15:32:27
 */
@Api(value = "CouponStockController",tags = {"优惠券库存模块"})
@RestController
@RequestMapping("/couponStock")
public class CouponStockController {
    // 测试
    /**
     * 服务对象
     */
    private final CouponStockService couponStockService;
    private final RedisTemplate redisTemplate;
    public CouponStockController(CouponStockService couponStockService, RedisTemplate redisTemplate) {
        this.couponStockService = couponStockService;
        this.redisTemplate = redisTemplate;
    }

    @Resource
    private WebSocketProcess webSocketProcess;

    @ApiOperation(value = "查询所有优惠券")
    @GetMapping("/getAll")
    public ResultVo<List<CouponStock>> getAll() {
        List<CouponStock> list = couponStockService.list();
        if (list.size() != 0) return ResultUtils.success(ResultMsg.SUCCESS_MSG, StatusCode.SUCCESS_CODE,list);
        else return ResultUtils.error(ResultMsg.DATA_NULL, StatusCode.SYSTEM_ERROR_CODE,null);
    }

    @ApiOperation(value = "发布优惠券")
    @PostMapping("/publishCoupon")
    public ResultVo<CouponStock> publishCoupon(@RequestBody CouponStock couponStock) throws Exception {
        boolean flag = couponStockService.save(couponStock);
        if (flag) webSocketProcess.sendAllMessage("已发布优惠券");
        if (flag) return ResultUtils.success(ResultMsg.SUCCESS_MSG, StatusCode.SUCCESS_CODE,flag);
        else return ResultUtils.error(ResultMsg.ERROR_MSG, StatusCode.SYSTEM_ERROR_CODE,flag);
    }

    @ApiOperation(value = "修改优惠券")
    @PutMapping("/updateCoupon")
    public ResultVo<CouponStock> updateCoupon(@RequestBody CouponStock couponStock) {
        LambdaQueryWrapper<CouponStock> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CouponStock::getCouponNo,couponStock.getCouponNo());
        boolean flag = couponStockService.update(queryWrapper);
        if (flag) return ResultUtils.success(ResultMsg.SUCCESS_MSG, StatusCode.SUCCESS_CODE,flag);
        else return ResultUtils.error(ResultMsg.ERROR_MSG, StatusCode.SYSTEM_ERROR_CODE,flag);
    }

    @ApiOperation(value = "注销优惠券")
    @DeleteMapping("/deleteByCoupon")
    public ResultVo<CouponStock> deleteByCoupon(@RequestBody CouponStock couponStock) {
        LambdaQueryWrapper<CouponStock> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(CouponStock::getStockId,couponStock.getStockId());
        boolean flag = couponStockService.remove(queryWrapper);
        if (flag) return ResultUtils.success(ResultMsg.SUCCESS_MSG, StatusCode.SUCCESS_CODE,flag);
        else return ResultUtils.error(ResultMsg.ERROR_MSG, StatusCode.SYSTEM_ERROR_CODE,flag);
    }


    //优惠券的分页查询
    @ApiOperation(value = "优惠券的分页查询")
    @GetMapping("/selectByPage")
    public ResultVo<CouponStock> selectByPage(@RequestParam Integer currentPage,@RequestParam Integer pageSize){
        IPage<CouponStock> page=couponStockService.selectByPage(currentPage,pageSize);
        return ResultUtils.success(ResultMsg.SUCCESS_MSG,StatusCode.PHONE_CODE_SUCCESS,page);
    }

    /**
     * 通过主键查询单条数据
     * @param couponNo
     * @return 单条数据
     */
    @ApiOperation(value = "查询优惠券记录")
    @GetMapping("/getByCouponNo/{couponNo}")
    public ResultVo<CouponStock> selectByCouponNo(@PathVariable Integer couponNo) {
        ResultVo<CouponStock> resultVo = new ResultVo<CouponStock>();
        CouponStock stock = couponStockService.getByCouponNo(couponNo);
        stock.setCouponStartDate(LocalDateTime.now());
        if (stock != null) {
            resultVo.setMsg(ResultMsg.SUCCESS_MSG);
            resultVo.setCode(StatusCode.SUCCESS_CODE);
        } else {
            resultVo.setMsg(ResultMsg.SUCCESS_MSG);
            resultVo.setCode(StatusCode.SUCCESS_CODE);
        }
        System.out.println(stock);
        resultVo.setData(stock);
        return resultVo;
    }

    /**
     * 根据优惠券编号删除数据
     * @param  couponNo
     * @return 删除结果
     */
    @ApiOperation(value = "根据优惠券编号注销优惠券")
    @DeleteMapping("/deleteByCouponNo")
    public ResultVo<CouponStock> deleteByCouponNo(@RequestParam(value = "couponNo") Integer couponNo) {
        boolean flag = couponStockService.removeByCouponNo(couponNo);
        if (flag) return ResultUtils.success(ResultMsg.SUCCESS_MSG,StatusCode.SUCCESS_CODE,null);
        else return ResultUtils.error(ResultMsg.DATA_NULL,StatusCode.SYSTEM_ERROR_CODE,null);
    }

    /**
     * 条件查询
     * @param couponName
     * @param couponNo
     * @param couponStatusNo
     * @return
     */
    @ApiOperation(value = "模糊查询")
    @GetMapping("/getListByCondition")
    public ResultVo<List<CouponStock>> getListByCondition(@RequestParam(value = "couponName",required = false) String couponName,@RequestParam(value = "couponNo",required = false) String couponNo,@RequestParam(value = "couponStatusNo",required = false) String couponStatusNo) {
        List<CouponStock> list = couponStockService.getListByCondition(couponName, couponNo,couponStatusNo);
        if (list.size() != 0) return ResultUtils.success(ResultMsg.SUCCESS_MSG,StatusCode.SUCCESS_CODE,list);
        else return ResultUtils.error(ResultMsg.DATA_NULL,StatusCode.SYSTEM_ERROR_CODE,list);
    }

    /**
     * 优惠券适用方编号查询
     * @param couponStatusNo
     * @return
     */
    @ApiOperation(value = "优惠券适用方编号查询")
    @GetMapping("/getListByHotelNo/{couponStatusNo}")
    public ResultVo<List<CouponStock>> getListByHotelNo(@PathVariable Integer couponStatusNo) {
        List<CouponStock> list = couponStockService.getListCouponByHotelNo(couponStatusNo);
        if (list.size() != 0) return ResultUtils.success(ResultMsg.SUCCESS_MSG,StatusCode.SUCCESS_CODE,list);
        else return ResultUtils.error(ResultMsg.DATA_NULL,StatusCode.SYSTEM_ERROR_CODE,list);
    }

    /**
     * 只获取当日的优惠券
     * @return
     */
    @ApiOperation(value = "当日优惠券获取")
    @GetMapping("/getTodayCouponList")
    public ResultVo<List<CouponStock>> getTodayCouponList() {
        List<CouponStock> list = couponStockService.list().stream().filter(s ->
                        // 优惠券的开始日期的天是否等于当前时间的天
                        s.getCouponStartDate().getDayOfMonth() == LocalDateTime.now().getDayOfMonth())
                // 发布方只能是平台的
                .filter(s->s.getCouponPublish()==0)
                .collect(Collectors.toList());
        if (list.size() != 0) {
            // 将当日优惠券记录放入缓存中
//            redisTemplate.opsForValue().set(RedisKey.TODAYCOUPONLIST,list);
            return ResultUtils.success(ResultMsg.SUCCESS_MSG,StatusCode.SUCCESS_CODE,list);
        } else return ResultUtils.error(ResultMsg.DATA_NULL,StatusCode.SYSTEM_ERROR_CODE,null);
    }

    /**
     * 根据优惠券编号修改优惠券库存记录
     * @param couponNo
     * @return
     */
    @ApiOperation(value = "根据优惠券编号修改优惠券库存记录")
    @PutMapping("/reduceCouponStockByCouponNo")
    public ResultVo<String> reduceCouponStockByCouponNo(@RequestParam(value = "couponNo") String couponNo) {
        String str = couponStockService.reduceCouponStock(couponNo);
        if (str.equals(ResultMsg.SECKIL_COUPON_SUCCESS))
            return ResultUtils.success(str,StatusCode.SUCCESS_CODE,str);
        else if (str.equals(ResultMsg.COUPON_STOCK_NULL))
            return ResultUtils.error(str,StatusCode.SYSTEM_ERROR_CODE,str);
        else
            return ResultUtils.error(str,StatusCode.SYSTEM_ERROR_CODE,str);
    }


    /**
     * 定时发布优惠券
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "定时发布优惠券")
//    @Scheduled(cron = "0 0 18 * * ?") // 每天18:00发布
//    @Scheduled(cron = "0/30 * * * * ?") // 每30s发布一次
    @Scheduled(cron = "0 0 17 * * ?") // 每天17:00发布
    @PostMapping("/timingPublishCoupon")
    public ResultVo<CouponStock> timingPublishCoupon() throws Exception {
        CouponStock couponStock = new CouponStock();
        Random random = new Random();
        Integer couponNo = random.nextInt(1000000);
        couponStock.setCouponNo(String.valueOf(couponNo)); // 优惠券编号
        couponStock.setCouponName("折扣券");
        couponStock.setCouponPublish(1);
        couponStock.setCouponDiscount(5.5); // 5.5折
        couponStock.setVersion(0); // 行锁
        couponStock.setCouponStartDate(LocalDateTime.now()); // 发布时间
        couponStock.setCouponEndDate(LocalDateTime.now().plusDays(7)); // 过期时间
        couponStock.setCouponFullPrice(0.0); // 满减条件
        couponStock.setCouponPrice(0.0); // 折扣价
        couponStock.setCouponSnapupStatus(0); // 抢购状态
        couponStock.setStock(10); // 库存量
        couponStock.setPublishTotal(10); // 发布量
        couponStock.setCouponAttention("仅限有效期内使用...");
        couponStock.setCouponStatusNo(0); // 适用全平台

        boolean flag = couponStockService.save(couponStock);
        if (flag) webSocketProcess.sendAllMessage("已发布优惠券");
        if (flag) return ResultUtils.success(ResultMsg.SUCCESS_MSG, StatusCode.SUCCESS_CODE,flag);
        else return ResultUtils.error(ResultMsg.ERROR_MSG, StatusCode.SYSTEM_ERROR_CODE,flag);
    }
}

